package cn.longwingstech.intelligence.agent.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.io.FileUtil;
import cn.longwingstech.intelligence.agent.aop.RateLimiter;
import cn.longwingstech.intelligence.agent.common.BaseResponse;
import cn.longwingstech.intelligence.agent.common.ResultUtils;
import cn.longwingstech.intelligence.agent.config.WebConfig;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/file")
@Tag(name = "文件管理控制层")
@SaCheckLogin
public class FileController {

    @PostMapping("/upload")
    @Operation(summary = "上传文件", description = "上传文件")
    @RateLimiter(key = "upload", time = 60, count = 10)
    public BaseResponse<String> upload(@RequestPart("file") MultipartFile file) {
        // 获取文件后缀
        String fileName = file.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        String newFileName = System.currentTimeMillis() + suffix;
        String savePath = WebConfig.UPLOAD_FOLDER + File.separatorChar + newFileName;

        try {
            FileUtil.writeBytes(file.getBytes(), savePath);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        String url = "https://api.longwingstech.cn/api/img/" + newFileName;
        return ResultUtils.success(url);
    }

}
